package com.skyworth.web.order.controller;

import com.skyworth.utils.StrUtil;
import com.skyworth.web.order.domain.OrderModel;
import com.skyworth.web.order.domain.ParentOrderModel;
import com.skyworth.web.order.form.OrderForm;
import com.skyworth.web.order.service.NewOrderService;
import com.skyworth.web.ordermenu.OrderMenuModel;
import com.skyworth.web.ordermenu.OrderMenuService;
import com.skyworth.web.wechat.common.AppSecretInfo;
import com.skyworth.web.wechat.engin.ServerEngin;
import com.skyworth.web.wechat.entity.AccessTokenModel;
import com.skyworth.web.wechat.protocol.NotifyMsg;
import com.skyworth.web.wechat.service.AccessTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yuhaichao on 2016/9/27.
 */
@Controller
@RequestMapping("waiterOrder")
public class WaiterOrderController {

    private static final Logger log = LoggerFactory.getLogger(WaiterOrderController.class);

    @Autowired
    private NewOrderService newOrderService;

    @Autowired
    private OrderMenuService orderMenuService;

    @Autowired
    private AccessTokenService accessTokenService;

    /**
     * 服务员添加一个订单
     * @param orderForm
     * @param model
     * @return
     */
    @RequestMapping(value = {"/api/order/"}, method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> create(HttpServletResponse response, @ModelAttribute OrderForm orderForm, Model model) {
        Map<String,Object> result = new HashMap<>();
        try {
            System.out.println(orderForm);
            System.out.println("tableId:" + orderForm.getTableId() + ",state:" + orderForm.getState());
            if (orderForm == null) {
                result.put("status", "error");
                return result;
            }

            OrderModel orderModel = OrderForm.toOrderModel(orderForm);
            ParentOrderModel parentOrderModel = OrderForm.toParentOrderModel(orderForm);
            orderModel = newOrderService.saveOrUpdate(parentOrderModel, orderModel, orderForm.getFoods());

            if (orderModel != null) {
                Map<String,Object> orderMap = newOrderService.getCurrentTableNoPayOrder(orderModel.userId);
                List<OrderMenuModel> menuList = orderMenuService.findByNoPayOrderId(orderModel.parentId);
                result.put("status", "success");
                result.put("order",orderMap);
                result.put("menu",menuList);
            } else {
                result.put("status", "error");
            }
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * 服务员端获取店铺里未支付的分页订单列表(列表的orderId为父订单的id)
     * @param storeId
     * @param page
     * @return
     */
    @RequestMapping(value = {"/api/getStoreNopayOrder/{storeId}/{page}"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getStoreNopayOrder(@PathVariable("storeId") long storeId, @PathVariable("page") int page){
        try{
            return newOrderService.getStoreNopayOrder(storeId,page,50);
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

    @RequestMapping(value = {"/api/getCurrentTableOrder/{userId}"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getCurrentTableNoPayOrder(@PathVariable("userId") String userId){
        try {
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> order = newOrderService.getCurrentTableNoPayOrder(userId);
            List<OrderMenuModel> menu = null;
            if (order != null) {
                long parentId = Long.parseLong(StrUtil.objectToString(order.get("orderId")));
                menu = orderMenuService.findByNoPayOrderId(parentId);
            }
            map.put("order", order);
            map.put("menu", menu);
            return map;
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }
    /**
     * 服务员端获取店铺里等待确认的订单列表(订单列表里的id是子订单的id)
     * @param storeId
     * @param page
     * @return
     */
    @RequestMapping(value = {"/api/getStoreConfirmOrder/{storeId}/{page}"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getStoreConfirmOrder(@PathVariable("storeId") long storeId, @PathVariable("page") int page){
        try{
            return newOrderService.getStoreConfirmOrder(storeId,page,50);
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * 点击等待确认的子订单列表中的一个item，只显示这个子订单的菜单和订单数据。
     * @param subOrderId
     * @return
     */
    @RequestMapping(value = {"/api/getSubOrderById/{subOrderId}"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getSubOrderById(@PathVariable("subOrderId") long subOrderId){
        try{
            Map<String,Object> map = new HashMap<>();
            Map<String,Object> subOrder = newOrderService.getSubOrderById(subOrderId);
            List<OrderMenuModel> menu = null;
            if(subOrder!=null){
                long subId = Long.parseLong(StrUtil.objectToString(subOrder.get("orderId")));
                menu = orderMenuService.findBySubOrderId(subId);
            }
            map.put("order",subOrder);
            map.put("menu",menu);
            return map;
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return null;
    }


    /**
     * 点击父订单列表中的一个item，显示这个父订单合并信息，以及合并的菜单列表(包括已完成的列表项，正在进行中的列表项的点击都用这个)
     * @param parentOrderId
     * @return
     */
    @RequestMapping(value = {"/api/getParentOrderById/{parentOrderId}"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getParentOrderById(@PathVariable("parentOrderId") long parentOrderId){
        try{
            ParentOrderModel parentOrderModel = newOrderService.getParentOrderById(parentOrderId);
            if(parentOrderModel==null){
                return null;
            }
            Map<String,Object> map = new HashMap<>();
            if(NewOrderService.ORDER_WECHAT_PAYED==parentOrderModel.getState()) {
                Map<String, Object> subOrder = newOrderService.getParentPayOrderDetail(parentOrderId);
                List<OrderMenuModel> menu = null;
                if (subOrder != null) {
                    long parentId = Long.parseLong(StrUtil.objectToString(subOrder.get("orderId")));
                    menu = orderMenuService.findByPayOrderId(parentId);
                }
                map.put("order", subOrder);
                map.put("menu", menu);
            }else if(NewOrderService.ORDER_CONFIRMED==parentOrderModel.getState()){
                Map<String, Object> subOrder = newOrderService.getParentNoPayOrderDetail(parentOrderId);
                List<OrderMenuModel> menu = null;
                if (subOrder != null) {
                    long parentId = Long.parseLong(StrUtil.objectToString(subOrder.get("orderId")));
                    menu = orderMenuService.findByNoPayOrderId(parentId);
                }
                map.put("order", subOrder);
                map.put("menu", menu);
            }
            return map;
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * 服务员拒绝订单接口
     * @param subOrderId
     * @return
     */
    @RequestMapping(value = {"/api/refuseOrder/{subOrderId}"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> refuseOrder(@PathVariable("subOrderId") long subOrderId){
        Map<String,Object> map = new HashMap<>();
        try{
            newOrderService.refuseOrder(subOrderId);
            map.put("status","success");
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return map;
    }

    /**
     * 服务员同意订单接口
     * @param subOrderId
     * @return
     */
    @RequestMapping(value = {"/api/acceptOrder/{subOrderId}"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> acceptOrder(@PathVariable("subOrderId") long subOrderId){
        Map<String,Object> map = new HashMap<>();
        try{
            OrderModel orderModel =newOrderService.acceptOrder(subOrderId);

            final String openid = orderModel.userId;
            final String orderId = StrUtil.objectToString(orderModel.id);
            new Thread() {
                public void run() {

                    AccessTokenModel atm = accessTokenService.findByAppId(AppSecretInfo.appId);
                    String accessToken = atm.getAccessToken();
                    Map<Object, Object> handleMap = NotifyMsg.orderHandleMsg(openid, orderId);
                    ServerEngin.getInstance().sendTemplateMsg(accessToken, handleMap);
                }
            }.start();

            map.put("status","success");
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return map;
    }


    /**
     * 服务员删除订单中的一个菜(传订单菜单关系表的id)
     * @param id
     * @return
     */
    @RequestMapping(value = {"/api/delteMenuItem/{id}"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> delteMenuItem(@PathVariable("id") long id){
        Map<String,Object> map = new HashMap<>();
        try{

            OrderModel orderModel = newOrderService.removeMenuItem(id);
            if(orderModel!=null) {
                long parentOrderId = orderModel.parentId;
                //float price = orderModel.price;

                //Map<String, Object> parentOrder = null;
                List<OrderMenuModel> menu = null;
                //if(price>0) {
                Map<String, Object> parentOrder = newOrderService.getParentNoPayOrderDetail(parentOrderId);
                    if (parentOrder != null && parentOrder.get("orderId")!=null && !"".equals(parentOrder.get("orderId"))) {
                        long parentId = Long.parseLong(StrUtil.objectToString(parentOrder.get("orderId")));
                        menu = orderMenuService.findByNoPayOrderId(parentId);
                    }
                //}
                map.put("order",parentOrder);
                map.put("menu",menu);
                map.put("status", "success");
                return map;
            }
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return map;
    }

    /**
     * 线下支付
     * @param userId
     * @param parentOrderId
     * @return
     */
    @RequestMapping(value = {"/api/offlinePay/{userId}/{parentOrderId}"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> offlinePay(@PathVariable("userId") String userId,@PathVariable("parentOrderId") long parentOrderId){
        Map<String,Object> map = new HashMap<>();
        try{
            if(parentOrderId<=0 || userId==null || "".equals(userId)){
                return null;
            }
            newOrderService.offlinePay(parentOrderId,userId);

            map.put("status","success");
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return map;
    }

    /**
     * 获取订单更新通知
     * @param storeId
     * @param lastUpdateDate
     * @return
     */
    @RequestMapping(value = {"/api/getOrderNotifyList/{storeId}"}, method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> getOrderNotifyList(@PathVariable("storeId") long storeId,@RequestParam("lastUpdateDate") String lastUpdateDate){
        try{
            return newOrderService.getOrderNotifyList(storeId,lastUpdateDate);
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return null;
    }


    /**
     * 获取台桌更新列表
     * @param storeId
     * @param lastUpdateDate
     * @return
     */
    @RequestMapping(value = {"/api/getTableNotifyList/{storeId}"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getTableNotifyList(@PathVariable("storeId") long storeId,@RequestParam(value = "lastUpdateDate",required = false) String lastUpdateDate){
        try{
            return newOrderService.getTableUpdateList(storeId,lastUpdateDate);
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * 获取当前时间
     * @return
     */
    @RequestMapping(value = {"/api/getCurrentUpdateDate"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getCurrentUpdateDate(){
        try{
            return newOrderService.getCurrentUpdateDate();
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

}
